#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import os
import sys

from xmldictHelper import XmlDict

MAXIDKEY = '..maxid'
MAXTYPEKEY = '..maxtypeid'

class ResDealer:
   #locate to res
   def __init__(self, src, dst):
      self.src = src
      self.dst = dst
      self.srcpublicxml = src + '/res/values/public.xml'
      self.dstpublicxml = dst + '/res/values/public.xml'
      self.xmldicthelper = XmlDict()
      self.srcdic = self.xmldicthelper.xml_to_dict(self.srcpublicxml)
      self.dstdic = self.xmldicthelper.xml_to_dict(self.dstpublicxml)
      self.newchangeid = True
      self.replaceid_dict={}


   def getdestid(self, dsttypedic, name, _type):
      retid=''
      if _type in dsttypedic:
         if name in dsttypedic[_type]:
            print('duplicate value:' + _type + ":" + name)
            return dsttypedic[_type][name]
         else:
            dsttypedic[_type][MAXIDKEY] = dsttypedic[_type][MAXIDKEY]+1
            retid = hex(dsttypedic[_type][MAXIDKEY])
      else:
         dsttypedic[MAXTYPEKEY] = (dsttypedic[MAXTYPEKEY] & 0xffff0000) + 0x00010000
         dsttypedic[_type] = {
            MAXIDKEY:dsttypedic[MAXTYPEKEY]
         }
         retid = hex(dsttypedic[MAXTYPEKEY])
      return retid


   def changeid(self, fromid, toid):
      print('prepare change id %s->%s'%(fromid, toid))
      cmd = 'sed -i "s/%s/%s/g" `grep "%s" -rl %s`'%(fromid, toid, fromid, 'smali*')
      #cmd = 'grep -r  "%s" %s'%(fromid, 'smali*')
      os.system(cmd)


   def cacheChangeIdToDict(self, fromid, toid):
      print('prepare change id %s->%s'%(fromid, toid))
      self.replaceid_dict[fromid] = toid


   def dochangeidinfile(self):
      print(len(self.replaceid_dict))
      if len(self.replaceid_dict) == 0:
         return
      cmd = 'egrep -rl "%s" %s'%('|'.join(self.replaceid_dict.keys()), "smali*")
      replacestr = ''
      for k,v in self.replaceid_dict.items():
         replacestr += ' -e "s/%s/%s/g"'%(k,v)

      cmd = 'sed -i %s `%s`'%(replacestr, cmd)
      os.system(cmd)


   def inserttag(self, value, dstdic):
      destid = self.getdestid(dstdic, value['@name'], value['@type'])
      if destid == '':
         print('todo error !!!')
         sys.exit(0)
      else:
         if self.newchangeid:
            self.cacheChangeIdToDict(value['@id'], destid)
         else:
            self.changeid(value['@id'], destid)
         #value['@id'] = destid #no need this
         dstdic[value['@type']][value['@name']] = destid


   '''
   1.load dst public.xml
   2.load src public.xml
   遍历src  type/name id
      添加到尾部，修改id
   '''
   def deal(self):
      #xml to dic
      dsttypedic=dict()
      dsttypedic[MAXTYPEKEY] = 0
      for dstvalue in self.dstdic['resources']['public']: #TODO what if dstdict is null!!!!???
         dsttypedic.setdefault(dstvalue['@type'], {})
         dsttypedic[dstvalue['@type']][dstvalue['@name']]=dstvalue['@id']
         idintval = int(dstvalue['@id'],16)
         if idintval > dsttypedic[dstvalue['@type']].get(MAXIDKEY,0):
            dsttypedic[dstvalue['@type']][MAXIDKEY] = idintval
            if idintval > dsttypedic[MAXTYPEKEY]:
               dsttypedic[MAXTYPEKEY] = idintval

      cwd = os.getcwd()
      os.chdir(self.src)
      srcpublic = self.srcdic.get('resources')
      srcpublic = srcpublic.get('public') if srcpublic else None
      if type(srcpublic) == list:
         for srcvalue in srcpublic:
            self.inserttag(srcvalue, dsttypedic)
      elif type(srcpublic) == dict:
         self.inserttag(srcpublic, dsttypedic)
      else:
         pass
      if self.newchangeid:
         self.dochangeidinfile()

      #dic to xml
      self.dstdic['resources']['public']=[]
      for _type,_values in dsttypedic.items():
         if _type == MAXTYPEKEY:
            continue
         for _name,_id in _values.items():
            if _name == MAXIDKEY:
               continue
            self.dstdic['resources']['public'].append({'@type':_type, '@name':_name, '@id': _id})

      ret = self.xmldicthelper.dicttoxml(self.dstdic)
      writetofile('dst.xml', ret)
      os.chdir(cwd)


def writetofile(path, content):
   with open(path,'wb') as f:
      if isinstance(content, str):
         f.write(content.encode('utf-8'))
      else:
         f.write(content)


if __name__ == "__main__":
   if(len(sys.argv) != 3):
	   print('src dst')
	   sys.exit(0)
   src = sys.argv[1]
   dst = sys.argv[2]
   dealer = ResDealer(src, dst)
   dealer.deal()
